package dal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.Vector;

/**
 * Singleton para obtener una instancia del pool de conexiones.
 * @author dcamarro
 *
 */
public class PoolConnection
{
	private Vector <Connection> connections = new Vector<Connection>();
	private String driver;
	private String jdbc_url;
	private String usuario;
	private String password;
	private int cantCon;
	private ResourceBundle resourceProperty = null;
	private final String NOMBRE_PROPERTY = "databaseConnection";

	private static PoolConnection pool;
	
	private PoolConnection()
	{
		getConfiguration();
		for (int i= 0; i< cantCon;i++)
			connections.add(connect());
	}
	
	/**
	 * Metodo por el cual accedemos a la instancia.
	 * @return PoolConnection
	 */
	public static PoolConnection getPoolConnection()
	{
		if (pool== null)
			pool =new PoolConnection();
		return pool;
	}
	
	private Connection connect()
	{
		try
		{
			Class.forName(driver);
            String dbConnectString = jdbc_url; 
            Connection con = DriverManager.getConnection (dbConnectString, usuario, password);
            return con;
		}
		catch (SQLException e)
		{
			System.out.println(e.getMessage());
			return null;
		}
		catch (Exception ex)
		{
			System.out.println(ex.getMessage());
			return null;
		}
	}
	
	private void getConfiguration()
	{
		this.resourceProperty = ResourceBundle.getBundle(NOMBRE_PROPERTY);
		try 
	    {
		   driver  =  resourceProperty.getString("jdbc.driverClassName");
	       jdbc_url = resourceProperty.getString("jdbc.url"); 
	       usuario = resourceProperty.getString("jdbc.username");
	       password = resourceProperty.getString("jdbc.password");
	       cantCon = Integer.parseInt(resourceProperty.getString("numero.conexiones").trim());
	       
	     } 
	    catch (Exception e) 
	     {
	     }
}
	
	/**
	 * Metodo que cierra todas las conexiones del poo de conexiones.
	 */
	public void closeConnections()
	{
		for (Connection conexion : connections) {
			try {
				conexion.close();
				
			} catch (SQLException e) {
			}
		}
		
	}
	
	/**
	 * Nos da una conexion del pool de conexiones.
	 * @return Connection perteneciente al pool
	 */
	public  Connection getConnection()
	{
		Connection c = null;
		if (connections.size()>0){
			c = connections.remove(0);
		}
		else
		{
		}
		
		return c;
	}
	
	/**
	 * Retorna la conexion al pool de conexiones
	 * @param c
	 */
	public void realeaseConnection(Connection c)
	{
		connections.add(c);
	}
}
